<?php

//error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
//ini_set('display_errors','On');

use Doctrine\Common\Collections\ArrayCollection;

class Admin_ImpresionesController extends Zend_Controller_Action {

    private $clienteDao;
    private $creditoDao;
    private $promesasDao;
    private $referenciaDao;
    private $fullPath;
    private $personaDao;
    private $pagoDao;

    public function init() {
        $auth = Zend_Auth::getInstance();

        if ($auth->hasIdentity()) {
            if (!empty($auth->getIdentity()->id)) {
                $usuarioDao = new Doctrine_Model_UsuariosDoctrineDao();
                $this->view->usuario = $usuarioDao->obtenerPorId($auth->getIdentity()->id);
            }
        } else {
            $this->_helper->redirector('index', 'login', 'admin');
        }

        /* Colores */
        $colores = array(
            '5b92d6' => array('5b92d6', '8fbaef'), //azul
            'd6d65b' => array('d6d65b', 'bfbf3f'), //amarillo
            '51ad56' => array('51ad56', '73be78'), //verde
            'db6f70' => array('db6f70', 'e59899'), //rojo
            '5e71a0' => array('5e71a0', '8e9cbc'), //azul oscuro
            'd68e5b' => array('d68e5b', 'e8a97c'), //naranja
            '92989f' => array('92989f', 'bbbec3')); //gris
        $this->view->colorSucursal = $colores[$this->view->usuario->getSucursal()->getColor()];
        /* Colores */

        $this->fullPath = $_SERVER["DOCUMENT_ROOT"];
        $this->pathUpload = 'financiera/adjuntos/';

        $this->personaDao = new Doctrine_Model_PersonaDao();
        $this->pagoDao = new Doctrine_Model_PagosDao();
        $this->creditoDao = new Doctrine_Model_CreditoDao();
        $this->promesasDao = new Doctrine_Model_PromesasDao();
        $this->referenciaDao = new Doctrine_Model_Referencias();

        $this->view->titulo = "Impresiones";
    }

    public function indexAction() {
        
    }

    public function ventasAction() {
        set_time_limit(0);
        ini_set("memory_limit", "512M");
        
        $desde = $this->getRequest()->getParam('desde', date('d/m/Y'));
        $hasta = $this->getRequest()->getParam('hasta', date('d/m/Y'));
        $numero = $this->getRequest()->getParam('numero', null);


        $estado = $this->getRequest()->getParam('estado', 'todos');
        $filtro_pagos = $this->getRequest()->getParam('filtro_pagos', 'todos');
        $con_venta = $this->getRequest()->getParam('con_venta', null);

        if (!empty($desde) && !empty($hasta)) {
            $this->view->desde = $desde;
            $this->view->hasta = $hasta;
            $this->view->filtro_pagos = $filtro_pagos;
            $this->view->con_venta = $con_venta;
            $desdeArray = explode('/', $desde);
            $hastaArray = explode('/', $hasta);
            $fechaDesde = $desdeArray[2] . '-' . $desdeArray[1] . '-' . $desdeArray[0]. ' ' ."00:00:00";
            $fechaHasta = $hastaArray[2] . '-' . $hastaArray[1] . '-' . $hastaArray[0]. ' ' ."23:59:59";

            $this->pagosDao = new Doctrine_Model_PagosDao();

            $sucursalId = $this->view->usuario->getSucursal()->getId();
            switch ($filtro_pagos) {
                case 'impresos':
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalImpresosFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;
                case 'noimpresos':
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalNoImpresosFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;
                default:
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;
            }
            $this->view->pagos = $pagos;
        } else {
            $pagos = new ArrayCollection();
            $ya_reimpresos = $this->getRequest()->getParam('ya_reimpresos', null);
            $con_venta = $this->getRequest()->getParam('con_venta', null);
            $this->view->ya_reimpresos = $ya_reimpresos;
            $this->view->con_venta = $con_venta;
            if (!empty($numero)) {
                $sucursalId = $this->view->usuario->getSucursal()->getId();
                $creditos = $this->creditoDao->obtenerPorNroCredito($numero, $sucursalId);
                foreach ($creditos as $credito) {
                    foreach ($credito->getCuotas() as $cuota) {
                        foreach ($cuota->getPagos() as $p) {
                            if ($filtro_pagos == 'todos') {
                                $pagos->add($p);
                            }
                            if ($filtro_pagos == 'impresos') {
                                $pagos->add($p);
                            }
                            if ($filtro_pagos == 'noimpresos') {
                                $pagos->add($p);
                            }
                        }
                    }
                }
            }
        }

        $this->view->filtros_pagos = $filtro_pagos;
        $this->view->pagos = $pagos;
        $this->view->numero = $numero;
    }

    function imprimirOtorgacion($credito_id, $pdf, $yaImpresos, $conOtorgacion) {
        
    }

    public function generarpdfAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        set_time_limit(0);

        ini_set("memory_limit", "512M");
        $desde = $this->getRequest()->getParam('desde', date('d/m/Y'));
        $hasta = $this->getRequest()->getParam('hasta', date('d/m/Y'));
        $desde = str_replace("_", "/", $desde);
        $hasta = str_replace("_", "/", $hasta);
        $estado = $this->getRequest()->getParam('estado', 'todos');
        $ya_reimpresos = $this->getRequest()->getParam('ya_reimpresos', null);
        $con_venta = $this->getRequest()->getParam('con_venta', null);
        $numeroDeCredito = $this->getRequest()->getParam('numero', null);
        if ($numeroDeCredito) {
            $sucursalId = $this->view->usuario->getSucursal()->getId();
            $creditos = $this->creditoDao->obtenerPorNroCredito($numeroDeCredito, $sucursalId);

            if (!$ya_reimpresos) {
                $c = new ArrayCollection();
                foreach ($creditos as $credito) {
                    foreach ($credito->getCuotas() as $cuota) {
                        if (!$cuota->tienePagosReimpresos() && ($cuota->getEstado()->getId() == 2 || $cuota->getEstado()->getId() == 3 || $cuota->getEstado()->getId() == 48 )) {
                            if (!$c->contains($credito)) {
                                $c->add($credito);
                            }
                        }
                    }
                }
                $creditos = $c;
            } else {
                $c = new ArrayCollection();
                foreach ($creditos as $credito) {
                    foreach ($credito->getCuotas() as $cuota) {
                        if ($cuota->getEstado()->getId() == 2 || $cuota->getEstado()->getId() == 3 || $cuota->getEstado()->getId() == 48) {
                            if (!$c->contains($credito)) {
                                $c->add($credito);
                            }
                        }
                    }
                }
                $creditos = $c;
            }
        } else {
            if (!empty($desde) && !empty($hasta)) {
                $this->view->desde = $desde;
                $this->view->hasta = $hasta;
                $this->view->ya_reimpresos = $ya_reimpresos;
                $this->view->con_venta = $con_venta;
                $desdeArray = explode('/', $desde);
                $hastaArray = explode('/', $hasta);
                $fechaDesde = $desdeArray[2] . '-' . $desdeArray[1] . '-' . $desdeArray[0];
                $fechaHasta = $hastaArray[2] . '-' . $hastaArray[1] . '-' . $hastaArray[0];
                //    $promesasEncontradas = new ArrayCollection();
                $this->creditoDao = new Doctrine_Model_CreditoDao();

                $sucursalId = $this->view->usuario->getSucursal()->getId();
                $creditos = $this->creditoDao->obtenerTodosEntreFechasPorSucursalFacturados($fechaDesde, $fechaHasta, $sucursalId);
                if (!$ya_reimpresos) {
                    $c = new ArrayCollection();
                    foreach ($creditos as $credito) {
                        foreach ($credito->getCuotas() as $cuota) {
                            if (!$cuota->tienePagosReimpresos() && ($cuota->getEstado()->getId() == 2 || $cuota->getEstado()->getId() == 3 || $cuota->getEstado()->getId() == 48 )) {
                                if (!$c->contains($credito)) {
                                    $c->add($credito);
                                }
                            }
                        }
                    }
                    $creditos = $c;
                } else {
                    $c = new ArrayCollection();
                    foreach ($creditos as $credito) {
                        foreach ($credito->getCuotas() as $cuota) {
                            if ($cuota->getEstado()->getId() == 2 || $cuota->getEstado()->getId() == 3 || $cuota->getEstado()->getId() == 48) {
                                if (!$c->contains($credito)) {
                                    $c->add($credito);
                                }
                            }
                        }
                    }
                    $creditos = $c;
                }
            }
        }
        $pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);


        $c = -20;
        $f = 830;
        $d = 1;


        foreach ($creditos as $credito) {

            $usuario = new Doctrine_Model_Entities_Usuario();
            $usuario = $this->view->usuario;

            $cant_cuotas_credito = $credito->getNroCuotas();

            // create PDF
            //$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
            //$image = Zend_Pdf_Image::imageWithPath('imagenes/logoBlanco.jpg');

            $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_BOLD);


            if ($con_venta == "checked") {
                /* Recibo credyphone */
                //$page->drawImage($image, $c + 50, $f - 60, $c + 230, $f - 10);
                $f = $f - 20;
                $page->setFont($font, 18)
                        ->drawText('CREDYPHONE', $c + 75, $f);
                $f = $f - 10;
                $page->setFont($font, 10)
                        ->drawText('Sucursal: ', $c + 75, $f)
                        ->drawText(utf8_decode('Dirección: '), $c + 50, $f - 10)
                        ->drawText('Tel: ', $c + 75, $f - 20)
                        ->drawText("{$usuario->getSucursal()->getDescripcion()}", $c + 130, $f)
                        ->drawText(utf8_decode($usuario->getSucursal()->getDireccion()), $c + 115, $f - 10)
                        ->drawText($usuario->getSucursal()->getTelefonos(), $c + 100, $f - 20);

                //   $f -= -10;
                $f = $f - 40;
                $page->setFont($font, 15)
                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
                        /* ->drawText('OTORGACION', $c + 100, $f - 88) */
                        ->setFont($font, 10)
                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
                        ->drawText('Apellidos      : ', $c + 50, $f)
                        ->drawText('Nombres        : ', $c + 50, $f - 15)
                        ->drawText('Otorgado       : ', $c + 50, $f - 30)
                        ->drawText('Cant. Cuotas   : ', $c + 50, $f - 45)
                        ->drawText('Importe Cuota  : ', $c + 50, $f - 60)
                        ->drawText('Importe Total  : ', $c + 50, $f - 75);
                $page->setFont($font, 11)
                        ->drawText("{$credito->getCliente()->getApellido()}", $c + 150, $f)
                        ->drawText("{$credito->getCliente()->getNombres()}", $c + 150, $f - 15)
                        ->drawText("{$credito->getFecha()->format("d/m/Y")}", $c + 150, $f - 30)
                        ->drawText($cant_cuotas_credito, $c + 150, $f - 45)
                        ->drawText("$ {$credito->getCuotas()->first()->getMontoOriginal()}", $c + 150, $f - 60)
                        ->drawText("$ {$credito->getMonto()}", $c + 150, $f - 75);
                $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                $page->setLineWidth(0.2)
                        ->drawLine(0, (float) $f - 80, 600, (float) $f - 80);
                if ($f < 151) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 890;
                }


                $f = $f - 90;
                foreach ($credito->getCuotas() as $cuota) {
                    if (true) {
                        if ($ya_reimpresos) {
                            $pagos = $cuota->obtenerPagosNoReimpresos();
                        } else {
                            $pagos = $cuota->getPagos();
                        }
                        $primerPago = true;
                        foreach ($pagos as $pago) {
                            if ($primerPago) {
                                $f = $f - 25;
                                $page->setFont($font, 14)
                                        ->drawText('Cuota N: ', $c + 30, $f);
                                $page->setFont($font, 16)
                                        ->drawText("{$cuota->getNumeroDeCuota()}", $c + 120, $f);
                                $ppf = true;
                                $primerPago = false;
                                $pago->setReimpreso(true);
                                $f = $f - 5;
                            }
                            $val = 0;
//                            if (!$cuota->estoySaldada())
//                                $val = 1;$f = $f - 10;

                            $f = $f - 10;
                            //    if (!$cuota->estoySaldada()) {
//                                $page->setFont($font, 15)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
//                                        ->drawText('PAGO PARCIAL', $c + 100, $f - 88)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'));
                            //        }
                            $page->setFont($font, 14)
                                    ->drawText('Apellidos', $c + 30, $f)
                                    ->drawText('Nombres    : ', $c + 30, $f - 20)
                                    ->drawText('Emitido    : ', $c + 30, $f - 40)
                                    ->drawText('Efectivo   : ', $c + 30, $f - 60);
//                            if (!$credito->getSaldo() && ($cuota->getNumeroDeCuota() == $credito->getNroCuotas())) {
//                                $page->drawText("CREDITO CANCELADO", $c + 65, $f - 210);
//                            }
                            if ($pago) {
                                $page->setFont($font, 16)
                                        ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                                        ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                                        ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 120, $f - 40);
                                $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                                $pago->setReimpreso(true);
                                $this->pagoDao->guardar($pago);
                            }
                            if ($ppf) {
                                $ppf = false;
                                $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                                $page->setLineWidth(0.5)
                                        ->drawLine(0, (float) $f - 85, 600, (float) $f - 85);
                                $f = $f - 110;
                            } else {
                                $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                                $page->setLineWidth(0.5)
                                        ->drawLine(0, (float) $f - 60, 600, (float) $f - 60);
                                $f = $f - 110;
                            }
                            if ($f < 150) {

                                $pdf->pages[] = $page;
                                $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                                $f = 800;
                            }
                        }
                    }

                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 800;
                    }
                }



                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $d++;
                if ($f < 150) {
                    $page->setLineWidth(0.2)
                            ->drawLine(0, (float) $f, 600, (float) $f);
                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $f = $f + 20;

//             if ($d > 3) {
//                 break;
//            }
            } else {

                $f = $f - 40;

                foreach ($credito->getCuotas() as $cuota) {
                    if (true) {
                        if ($ya_reimpresos) {
                            $pagos = $cuota->obtenerPagosNoReimpresos();
                        } else {
                            $pagos = $cuota->getPagos();
                        }
                        $primerPago = true;
                        foreach ($pagos as $pago) {
                            if ($cuota->getNumeroDeCuota() == 5) {
                                $dd = 22;
                            }
                            if ($primerPago) {
                                $page->setFont($font, 14)
                                        ->drawText('Cuota N  :', $c + 30, $f);
                                $page->setFont($font, 16)
                                        ->drawText("{$cuota->getNumeroDeCuota()}", $c + 120, $f);
                                $primerPago = false;
                            }
                            $val = 0;
//                            if (!$cuota->estoySaldada())
//                                $val = 1;

                            $f = $f - 15;
//                            if (!$cuota->estoySaldada()) {
//                                $page->setFont($font, 15)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
//                                        ->drawText('PAGO PARCIAL', $c + 100, $f - 88)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'));
//                            }
                            $page->setFont($font, 14)
                                    ->drawText('Apellidos:', $c + 30, $f)
                                    ->drawText('Nombres  : ', $c + 30, $f - 20)
                                    ->drawText('Emitido  : ', $c + 30, $f - 40)
                                    ->drawText('Efectivo : ', $c + 30, $f - 60);
//                            if (!$credito->getSaldo() && ($cuota->getNumeroDeCuota() == $credito->getNroCuotas())) {
//                                $page->drawText("CREDITO CANCELADO", $c + 65, $f - 210);
//                            }
                            if ($pago) {
                                $page->setFont($font, 16)
                                        ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                                        ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                                        ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 140, $f - 40);
                                $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                                $pago->setReimpreso(true);
                                $this->pagoDao->guardar($pago);
                            }
                            $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                            $page->setLineWidth(0.5)
                                    ->drawLine(0, (float) $f - 100, 600, (float) $f - 100);
                            $f = $f - 120;
                            if ($f < 150) {

                                $pdf->pages[] = $page;
                                $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                                $f = 800;
                            }
                        }
                    }

                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 800;
                    }
                }



                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $d++;
                if ($f < 150) {
                    $page->setLineWidth(0.2)
                            ->drawLine(0, (float) $f, 600, (float) $f);
                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $f = $f + 20;

//                if ($d > 6) {
//                    break;
//                }
            }
        }
        $pdf->pages[] = $page;
        $fecha = new DateTime();
        $filename = "otorgacion_{$credito->getId()}_{$fecha->format("Ymd")}";
        //  $pdf->pages[] = $page;
        $this->getResponse()->setHeader('Content-type', 'application/pdf', true);
        $this->getResponse()->setHeader('Content-disposition', "inline; filename={$filename}.pdf", true);
        $this->getResponse()->setBody($pdf->render());
    }

    public function imprimirpagoindividualpdfAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        set_time_limit(0);

        ini_set("memory_limit", "512M");

        $pago_id = $this->getRequest()->getParam('pago_id', null);
        $con_venta = $this->getRequest()->getParam('con_venta', null);

        if ($pago_id) {
            $sucursalId = $this->view->usuario->getSucursal()->getId();
            $pago = $this->pagoDao->obtenerPorId($pago_id);
            $pago->setFechaReimpreso(new DateTime());
        }
        $pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);


        $c = -20;
        $f = 830;
        $d = 1;

        $creditos = new ArrayCollection();
        $credito = $pago->getCuota()->getCredito();
        $cuota = $pago->getCuota();
        $creditos->add($credito);
        foreach ($creditos as $credito) {

            $usuario = new Doctrine_Model_Entities_Usuario();
            $usuario = $this->view->usuario;



            // $credito = new Doctrine_Model_Entities_Credito();
            //   $credito = $this->creditoDao->obtenerPorId($credito_id);
            $cant_cuotas_credito = $credito->getNroCuotas();

            // create PDF
            //$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
            //$image = Zend_Pdf_Image::imageWithPath('imagenes/logoBlanco.jpg');

            $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_BOLD);

            if ($con_venta) {
                /* Recibo credyphone */
                //$page->drawImage($image, $c + 50, $f - 60, $c + 230, $f - 10);
                $f = $f - 20;
                $page->setFont($font, 18)
                        ->drawText('CREDYPHONE', $c + 75, $f);
                $f = $f - 10;
                $page->setFont($font, 10)
                        ->drawText('Sucursal: ', $c + 75, $f)
                        ->drawText(utf8_decode('Dirección: '), $c + 50, $f - 10)
                        ->drawText('Tel: ', $c + 75, $f - 20)
                        ->drawText("{$usuario->getSucursal()->getDescripcion()}", $c + 130, $f)
                        ->drawText(utf8_decode($usuario->getSucursal()->getDireccion()), $c + 115, $f - 10)
                        ->drawText($usuario->getSucursal()->getTelefonos(), $c + 100, $f - 20);

                //   $f -= -10;
                $f = $f - 40;
                $page->setFont($font, 15)
                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
                        /* ->drawText('OTORGACION', $c + 100, $f - 88) */
                        ->setFont($font, 10)
                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
                        ->drawText('Apellidos      : ', $c + 50, $f)
                        ->drawText('Nombres        : ', $c + 50, $f - 15)
                        ->drawText('Otorgado       : ', $c + 50, $f - 30)
                        ->drawText('Cant. Cuotas   : ', $c + 50, $f - 45)
                        ->drawText('Importe Cuota  : ', $c + 50, $f - 60)
                        ->drawText('Importe Total  : ', $c + 50, $f - 75);
                $page->setFont($font, 11)
                        ->drawText("{$credito->getCliente()->getApellido()}", $c + 150, $f)
                        ->drawText("{$credito->getCliente()->getNombres()}", $c + 150, $f - 15)
                        ->drawText("{$credito->getFecha()->format("d/m/Y")}", $c + 150, $f - 30)
                        ->drawText($cant_cuotas_credito, $c + 150, $f - 45)
                        ->drawText("$ {$credito->getCuotas()->first()->getMontoOriginal()}", $c + 150, $f - 60)
                        ->drawText("$ {$credito->getMonto()}", $c + 150, $f - 75);
                $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                $page->setLineWidth(0.2)
                        ->drawLine(0, (float) $f - 80, 600, (float) $f - 80);
                if ($f < 151) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 890;
                }


                $f = $f - 90;



                $f = $f - 25;
                $page->setFont($font, 14)
                        ->drawText('Cuota N: ', $c + 30, $f);
                $page->setFont($font, 16)
                        ->drawText("{$cuota->getNumeroDeCuota()}", $c + 120, $f);
                $ppf = true;
                $primerPago = false;
                $pago->setReimpreso(true);
                $f = $f - 5;

                $val = 0;


                $f = $f - 10;

                $page->setFont($font, 14)
                        ->drawText('Apellidos', $c + 30, $f)
                        ->drawText('Nombres    : ', $c + 30, $f - 20)
                        ->drawText('Emitido    : ', $c + 30, $f - 40)
                        ->drawText('Efectivo   : ', $c + 30, $f - 60);

                if ($pago) {
                    $page->setFont($font, 16)
                            ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                            ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                            ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 120, $f - 40);
                    $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                    $pago->setReimpreso(true);
                    $this->pagoDao->guardar($pago);
                }
                if ($ppf) {
                    $ppf = false;
                    $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                    $page->setLineWidth(0.5)
                            ->drawLine(0, (float) $f - 85, 600, (float) $f - 85);
                    $f = $f - 110;
                } else {
                    $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                    $page->setLineWidth(0.5)
                            ->drawLine(0, (float) $f - 60, 600, (float) $f - 60);
                    $f = $f - 110;
                }
                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 800;
                }


                $pdf->pages[] = $page;
                $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                $f = 830;
            } else {


                $val = 0;
//                            if (!$cuota->estoySaldada())
//                                $val = 1;

                $f = $f - 15;
//                            if (!$cuota->estoySaldada()) {
//                                $page->setFont($font, 15)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
//                                        ->drawText('PAGO PARCIAL', $c + 100, $f - 88)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'));
//                            }
                $page->setFont($font, 14)
                        ->drawText('Apellidos:', $c + 30, $f)
                        ->drawText('Nombres  : ', $c + 30, $f - 20)
                        ->drawText('Emitido  : ', $c + 30, $f - 40)
                        ->drawText('Efectivo : ', $c + 30, $f - 60);
//                            if (!$credito->getSaldo() && ($cuota->getNumeroDeCuota() == $credito->getNroCuotas())) {
//                                $page->drawText("CREDITO CANCELADO", $c + 65, $f - 210);
//                            }
                if ($pago) {
                    $page->setFont($font, 16)
                            ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                            ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                            ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 140, $f - 40);
                    $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                    $pago->setReimpreso(true);
                    $this->pagoDao->guardar($pago);
                }
                $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                $page->setLineWidth(0.5)
                        ->drawLine(0, (float) $f - 100, 600, (float) $f - 100);
                $f = $f - 120;
                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 800;
                }



                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 800;
                }




                if ($f < 150) {

                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $d++;
                if ($f < 150) {
                    $page->setLineWidth(0.2)
                            ->drawLine(0, (float) $f, 600, (float) $f);
                    $pdf->pages[] = $page;
                    $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                    $f = 830;
                }
                $f = $f + 20;

//                if ($d > 6) {
//                    break;
//                }
            }
        }
        $pdf->pages[] = $page;
        $fecha = new DateTime();
        $filename = "otorgacion_{$credito->getId()}_{$fecha->format("Ymd")}";
        //  $pdf->pages[] = $page;
        $this->getResponse()->setHeader('Content-type', 'application/pdf', true);
        $this->getResponse()->setHeader('Content-disposition', "inline; filename={$filename}.pdf", true);
        $this->getResponse()->setBody($pdf->render());
    }

    public function imprimirlistadosdepagospdfAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        set_time_limit(0);

        ini_set("memory_limit", "512M");
        $desde = $this->getRequest()->getParam('desde', date('d/m/Y'));
        $hasta = $this->getRequest()->getParam('hasta', date('d/m/Y'));
        $desde = str_replace("_", "/", $desde);
        $hasta = str_replace("_", "/", $hasta);

        $estado = $this->getRequest()->getParam('estado', 'todos');
        $filtro_pagos = $this->getRequest()->getParam('filtro_pagos', null);
        $con_venta = $this->getRequest()->getParam('con_venta', null);

        if (!empty($desde) && !empty($hasta)) {

            $this->view->desde = $desde;
            $this->view->hasta = $hasta;
            $this->view->ya_reimpresos = $ya_reimpresos;
            $this->view->con_venta = $con_venta;
            $desdeArray = explode('/', $desde);
            $hastaArray = explode('/', $hasta);
            $fechaDesde = $desdeArray[2] . '-' . $desdeArray[1] . '-' . $desdeArray[0];
            $fechaHasta = $hastaArray[2] . '-' . $hastaArray[1] . '-' . $hastaArray[0];
            //    $promesasEncontradas = new ArrayCollection();
            $this->pagosDao = new Doctrine_Model_PagosDao();

            $sucursalId = $this->view->usuario->getSucursal()->getId();

            switch ($filtro_pagos) {
                case 'impresos':
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalImpresosFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;
                case 'noimpresos':
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalNoImpresosFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;

                default:
                   
                    $pagos = $this->pagoDao->obtenerEntreFechasporSucursalFacturados($fechaDesde, $fechaHasta, $sucursalId);
                    break;
            }

            

            $this->view->pagos = $pagos;
        } else {
            $pagos = new ArrayCollection();
            $numero = $this->getRequest()->getParam('numero');
            $ya_reimpresos = $this->getRequest()->getParam('ya_reimpresos', null);
            $con_venta = $this->getRequest()->getParam('con_venta', null);
            $this->view->ya_reimpresos = $ya_reimpresos;
            $this->view->con_venta = $con_venta;
            if (!empty($numero)) {
                $sucursalId = $this->view->usuario->getSucursal()->getId();
                $creditos = $this->creditoDao->obtenerPorNroCredito($numero, $sucursalId);
                foreach ($creditos as $credito) {
                    foreach ($credito->getCuotas() as $cuota) {
                        foreach ($cuota->getPagos() as $p) {
                            if ($filtro_pagos == 'todos') {
                                $pagos->add($p);
                            }
                            if ($filtro_pagos == 'impresos') {
                                $pagos->add($p);
                            }
                            if ($filtro_pagos == 'noimpresos') {
                                $pagos->add($p);
                            }
                        }
                    }
                }
            }
        }
  
        $pdf = new Zend_Pdf();
        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);

        $c = -20;
        $f = 830;
        $d = 1;
        foreach ($pagos as $pago) {
           
            $con_venta = $this->getRequest()->getParam('con_venta', null);
            $pago->setFechaReimpreso(new DateTime());


            $creditos = new ArrayCollection();
            $credito = $pago->getCuota()->getCredito();
            $cuota = $pago->getCuota();
            $creditos->add($credito);
            foreach ($creditos as $credito) {

                $usuario = new Doctrine_Model_Entities_Usuario();
                $usuario = $this->view->usuario;

                $cant_cuotas_credito = $credito->getNroCuotas();

                // create PDF
                //$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                //$image = Zend_Pdf_Image::imageWithPath('imagenes/logoBlanco.jpg');

                $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_BOLD);

                if ($con_venta) {
                    /* Recibo credyphone */
                    //$page->drawImage($image, $c + 50, $f - 60, $c + 230, $f - 10);
                    $f = $f - 20;
                    $page->setFont($font, 18)
                            ->drawText('CREDYPHONE', $c + 75, $f);
                    $f = $f - 10;
                    $page->setFont($font, 10)
                            ->drawText('Sucursal: ', $c + 75, $f)
                            ->drawText(utf8_decode('Dirección: '), $c + 50, $f - 10)
                            ->drawText('Tel: ', $c + 75, $f - 20)
                            ->drawText("{$usuario->getSucursal()->getDescripcion()}", $c + 130, $f)
                            ->drawText(utf8_decode($usuario->getSucursal()->getDireccion()), $c + 115, $f - 10)
                            ->drawText($usuario->getSucursal()->getTelefonos(), $c + 100, $f - 20);

                    //   $f -= -10;
                    $f = $f - 40;
                    $page->setFont($font, 15)
                            ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
                            /* ->drawText('OTORGACION', $c + 100, $f - 88) */
                            ->setFont($font, 10)
                            ->setFillColor(Zend_Pdf_Color_Html::color('#000000'))
                            ->drawText('Apellidos      : ', $c + 50, $f)
                            ->drawText('Nombres        : ', $c + 50, $f - 15)
                            ->drawText('Otorgado       : ', $c + 50, $f - 30)
                            ->drawText('Cant. Cuotas   : ', $c + 50, $f - 45)
                            ->drawText('Importe Cuota  : ', $c + 50, $f - 60)
                            ->drawText('Importe Total  : ', $c + 50, $f - 75);
                    $page->setFont($font, 11)
                            ->drawText("{$credito->getCliente()->getApellido()}", $c + 150, $f)
                            ->drawText("{$credito->getCliente()->getNombres()}", $c + 150, $f - 15)
                            ->drawText("{$credito->getFecha()->format("d/m/Y")}", $c + 150, $f - 30)
                            ->drawText($cant_cuotas_credito, $c + 150, $f - 45)
                            ->drawText("$ {$credito->getCuotas()->first()->getMontoOriginal()}", $c + 150, $f - 60)
                            ->drawText("$ {$credito->getMonto()}", $c + 150, $f - 75);
                    $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                    $page->setLineWidth(0.2)
                            ->drawLine(0, (float) $f - 80, 600, (float) $f - 80);
                    if ($f < 151) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 890;
                    }


                    $f = $f - 90;



                    $f = $f - 25;
                    $page->setFont($font, 14)
                            ->drawText('Cuota N: ', $c + 30, $f);
                    $page->setFont($font, 16)
                            ->drawText("{$cuota->getNumeroDeCuota()}", $c + 120, $f);
                    $ppf = true;
                    $primerPago = false;
                    $pago->setReimpreso(true);
                    $f = $f - 5;

                    $val = 0;


                    $f = $f - 10;

                    $page->setFont($font, 14)
                            ->drawText('Apellidos', $c + 30, $f)
                            ->drawText('Nombres    : ', $c + 30, $f - 20)
                            ->drawText('Emitido    : ', $c + 30, $f - 40)
                            ->drawText('Efectivo   : ', $c + 30, $f - 60);

                    if ($pago) {
                        $page->setFont($font, 16)
                                ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                                ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                                ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 120, $f - 40);
                        $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                        $pago->setReimpreso(true);
                        $this->pagoDao->guardar($pago);
                    }
                    if ($ppf) {
                        $ppf = false;
                        $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                        $page->setLineWidth(0.5)
                                ->drawLine(0, (float) $f - 85, 600, (float) $f - 85);
                        $f = $f - 110;
                    } else {
                        $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                        $page->setLineWidth(0.5)
                                ->drawLine(0, (float) $f - 60, 600, (float) $f - 60);
                        $f = $f - 110;
                    }
                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 800;
                    }


                } else {


                    $val = 0;
//                            if (!$cuota->estoySaldada())
//                                $val = 1;

                    $f = $f - 15;
//                            if (!$cuota->estoySaldada()) {
//                                $page->setFont($font, 15)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#990000'))
//                                        ->drawText('PAGO PARCIAL', $c + 100, $f - 88)
//                                        ->setFillColor(Zend_Pdf_Color_Html::color('#000000'));
//                            }
                    $page->setFont($font, 14)
                            ->drawText('Apellidos:', $c + 30, $f)
                            ->drawText('Nombres  : ', $c + 30, $f - 20)
                            ->drawText('Emitido  : ', $c + 30, $f - 40)
                            ->drawText('Efectivo : ', $c + 30, $f - 60);
//                            if (!$credito->getSaldo() && ($cuota->getNumeroDeCuota() == $credito->getNroCuotas())) {
//                                $page->drawText("CREDITO CANCELADO", $c + 65, $f - 210);
//                            }
                    if ($pago) {
                        $page->setFont($font, 16)
                                ->drawText("{$credito->getCliente()->getApellido()}", $c + 120, $f)
                                ->drawText("{$credito->getCliente()->getNombres()}", $c + 120, $f - 20)
                                ->drawText("{$pago->getFecha()->format("d/m/Y")}", $c + 140, $f - 40);
                        $page->drawText("$ {$pago->getMonto()}", $c + 120, $f - 60);
                        $pago->setReimpreso(true);
                        $this->pagoDao->guardar($pago);
                    }
                    $page->setLineDashingPattern(array(3, 2, 3, 4), 1.6);
                    $page->setLineWidth(0.5)
                            ->drawLine(0, (float) $f - 100, 600, (float) $f - 100);
                    $f = $f - 120;
                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 800;
                    }



                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 800;
                    }




                    if ($f < 150) {

                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 830;
                    }
                    $d++;
                    if ($f < 150) {
                        $page->setLineWidth(0.2)
                                ->drawLine(0, (float) $f, 600, (float) $f);
                        $pdf->pages[] = $page;
                        $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                        $f = 830;
                    }
                    $f = $f + 20;

//                if ($d > 6) {
//                    break;
//                }
                }
            }
        }
        $pdf->pages[] = $page;
        $fecha = new DateTime();
        $filename = "otorgacion_";
        //  $pdf->pages[] = $page;
        $this->getResponse()->setHeader('Content-type', 'application/pdf', true);
        $this->getResponse()->setHeader('Content-disposition', "inline; filename={$filename}.pdf", true);
        $this->getResponse()->setBody($pdf->render());
    }

}

